package com.rkc.utils;

import com.rkc.model.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * @author `RKC`
 * @date 2021/10/16 16:53
 */
@Slf4j
public class JwtUtil {

    /**
     * token过期时间，7天
     */
    private static final long EXPIRE = 60 * 1000 * 60 * 24 * 7;

    /**
     * 秘钥
     */
    private static final String SECRET = "dynamicProgramming";

    /**
     * 令牌前缀
     */
    private static final String TOKEN_PREFIX = "shopping";

    private static final String SUBJECT = "rkc";

    /**
     * 根据用户信息生成token
     * @param loginUser
     * @return
     */
    public static String generateJsonWebToken(LoginUser loginUser) {
        if (loginUser == null) {
            throw new NullPointerException("对象不能为空");
        }
        return TOKEN_PREFIX + Jwts.builder().setSubject(SUBJECT)
                .claim("head_img", loginUser.getHeadImg())
                .claim("id", loginUser.getId())
                .claim("name", loginUser.getName())
                .claim("mail", loginUser.getMail())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public static Claims checkJWT(String token) {
        try {
            return Jwts.parser().setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody();
        } catch (Exception e) {
            log.info("jwt token解密失败");
            return null;
        }
    }
}
